import React, { useState } from 'react';
import { Upload, Button, Card, message, Image, Row, Col, Typography } from 'antd';
import { UploadOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { RcFile, UploadChangeParam } from 'antd/es/upload/interface';

const { Title } = Typography;

const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const ImageUpload: React.FC = () => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [loading, setLoading] = useState(false);

  const handleCancel = () => setPreviewOpen(false);

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    setFileList(info.fileList);
  };

  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
      return Upload.LIST_IGNORE;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片大小不能超过5MB!');
      return Upload.LIST_IGNORE;
    }
    return false;
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <div className="image-upload">
      <Title level={4} style={{ marginBottom: 16 }}>图片上传</Title>
      <Card>
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Upload
              listType="picture-card"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}
              beforeUpload={beforeUpload}
              multiple
              accept="image/*"
            >
              {fileList.length >= 8 ? null : uploadButton}
            </Upload>
          </Col>
          <Col span={24}>
            <Button
              type="primary"
              onClick={() => {
                if (fileList.length === 0) {
                  message.warning('请先选择图片');
                  return;
                }
                setLoading(true);
                // 模拟上传
                setTimeout(() => {
                  setLoading(false);
                  message.success('上传成功');
                  setFileList([]);
                }, 1500);
              }}
              loading={loading}
              icon={<UploadOutlined />}
            >
              {loading ? '上传中...' : '开始上传'}
            </Button>
            <Button
              style={{ marginLeft: 8 }}
              onClick={() => setFileList([])}
              disabled={fileList.length === 0}
            >
              清空
            </Button>
          </Col>
        </Row>
      </Card>

      {previewImage && (
        <Image
          wrapperStyle={{ display: 'none' }}
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => {
              setPreviewOpen(visible);
              if (!visible) {
                handleCancel();
              }
            },
            afterOpenChange: (visible) => !visible && setPreviewOpen(false),
          }}
          src={previewImage}
        />
      )}
    </div>
  );
};

export default ImageUpload;
